import React from 'react'
import { connect } from 'dva'
import LwjTable from 'components/LwjTable/LwjTable'
import queryString from 'query-string'
import { Button, Row, Col, Switch, Modal, Transfer, Popover, Table, InputNumber, Icon, message } from 'antd'
//常用组件
import PageHeaderLayout from 'components/Layout/PageHeaderLayout'
import GeneralFilter from 'components/Filter/GeneralFilter'
import { Page, Loader } from 'components'
//时间转化
import moment from 'moment'
//样式
import styles from './RecommendList.less'
let timer = null;
const RecommendList = ({location, dispatch, recommendlist, app, loading}) => {

    //数据
	const {
	    list,
    	queryParam,
    	products,
    	selectedRowKeys,
    	selectedRows
  	} = recommendlist;

    //导航栏
  	const breadcrumbList = [{
   		title: "商品管理"
  	}, {
    	title: "推荐商品"
  	}];

  	//筛选
	const filterProps = {
	    filterItems: [
	      {
	        type: 'input',
	        id: 'name',
	        title: '商品名称'
	      }
	    ],
	    onFilterChange(value) {
	    	dispatch({
	    		type: 'recommendlist/changeFilter',
	    		queryParam: value
	    	})
	      	dispatch({
		        type: 'recommendlist/query'
	      	})
	    },
	    Col: 6,
	    isExpand: true
	}

    // 表格属性
  	const tableProps = {
	    dataSource: list,
	    loading: loading.effects['recommendlist/query'],
	    pageChangeAction: 'recommendlist/query',
	    pagination: false,
	    dispatch,
	    rowSelection:{
		    onChange: (selectedRowKeys, selectedRows) => {
		        dispatch({
		          type: 'recommendlist/setSelectedRowKeys',
		          selectedRowKeys: selectedRowKeys,
		          selectedRows: selectedRows
		        })
	      	}
	    },
	    location,
	    locale:{
	      emptyText:"暂无推荐商品"
	    }
  	};

    //表格参数
  	const columns = [{
	      	title: '商品名称',
	      	dataIndex: 'name',
	     	key: 'name',
	      	width: '25%'
	    }, {
	      	title: '商品图片',
	      	dataIndex: 'goods_info',
	     	key: 'goods_info',
	      	width: '10%',
	      	render: (text, record) => {
	      		return (
	      			<Popover content={<img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productBigImg} />} title="商品图片" placement="right">
	      				<img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productSmallImg} />
	      			</Popover>
	      		)
	      	}
	    }, {
	      	title: '所属分类',
	      	dataIndex: 'cate_name',
	      	key: 'cate_name',
	      	width: '20%'
	    }, {
	      	title: '权重',
	      	dataIndex: 'sort',
	      	key: 'sort',
	      	width: '25%',
	      	render: (text, record, index) => {
	      		return (
	      			<div>
	      				<InputNumber min={0} value={record.sort} onChange={(value) => updateSort(record, index, value+'')} />
	      			</div>
	      		)
	      	}
	    }, {
	      	title: '操作',
	      	key: 'handle',
	      	width: '20%',
	      	render: (text, record) => {
	      		return (<a onClick={() => delRecommend([record])}>删除</a>)
	      	}
	    }
  	]

  	// 数量减
  	const updateSort=(item, index, sort)=>{
	    sort = sort.replace(/\D/g,'');
	    if(!sort || (sort == '')){
	      sort = 0;
	    }
	    list[index].sort = parseInt(sort);
	    dispatch({
	      type: 'recommendlist/success',
	      payload: {
	      	list
	      }
	    })
	    clearTimeout(timer);
	    timer = setTimeout(function(){
	    	let _temp = list.map((value) => {return {commodityId: value.id, sort: value.sort};});
	    	dispatch({
		        type: 'recommendlist/updateRecommend',
		        params: {
		        	recommendGoods: _temp
		        }
	     	})
	    },500)
  	}

  	const handleFormChange = (changedFields = {})=>{
	    let queryParam = {};
	    for( let key in changedFields){
	      queryParam[key] = changedFields[key].value
	    }
	    dispatch({
	      type: 'recommendlist/changeFilter',
	      queryParam: queryParam
	    })
  	}

	// 弹窗数据
	const productFilterProps = {
		filterItems: [
		  {
		    type: 'input',
		    id: 'name',
		    title: '商品名称'
		  },
		  // {
		  //   type: 'input',
		  //   id: 'cate_name',
		  //   title: '商品分类'
		  // },
		  {
		    type: 'input',
		    id: 'goods_id',
		    title: 'SPU编码'
		  }, {
		    type: 'input',
		    id: 'id',
		    title: 'SKU编码'
		  }
		],
		Col: 6,
		onFilterChange(value) {
		  dispatch({
		    type: 'recommendlist/changeParam',
		    queryParam: value
		  })
		  dispatch({
		    type: 'recommendlist/productList',
		    payload: {
		      start: 0,
		      limit: products.pagination.pageSize
		    }
		  })
		}
	}

	// 表格属性
	const productTableProps = {
		dataSource: products.list,
		loading: loading.effects['recommendlist/productList'],
		pagination: products.pagination,
		pageChangeAction: 'recommendlist/productList',
		dispatch,
		location,
		rowSelection:{
		  	onChange: (selectedRowKeys, selectedRows) => {
			    dispatch({
		      		type: 'recommendlist/setSelectedProductRows',
		      		selectedRowKeys: selectedRowKeys,
		      		selectedRows: selectedRows
			    })
		  	},
		  	selectedRowKeys: products.selectedRowKeys
		}
	};

	const productsColumns = [
		{
		  title: '商品名称',
		  dataIndex: 'name',
		  key: 'name',
		  width: '20%'
		}, {
		  title: '商品图片',
		  dataIndex: 'goods_info',
		  key: 'goods_info',
		  width: '15%',
		  render: (text, record) => {
		    return (
		      <Popover content={<img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productBigImg} />} title="商品图片" placement="right">
		        <img src={record.goods_info ? record.goods_info.cover_path : ''} className={styles.productSmallImg} />
		      </Popover>
		    )
		  }
		}, {
		  title: '商品分类',
		  dataIndex: 'cate_name',
		  key: 'cate_name',
		  width: '10%'
		}, {
		  title: 'SPU',
		  dataIndex: 'goods_id',
		  key: 'goods_id',
		  width: '10%'
		}, {
		  title: 'SKU',
		  dataIndex: 'sku_id',
		  key: 'sku_id',
		  width: '10%'
		}, {
		  title: '库存',
		  dataIndex: 'stock',
		  key: 'stock',
		  width: '8%'
		}, {
		  title: '状态',
		  dataIndex: 'status',
		  key: 'status',
		  width: '9%',
		  render: (text, record) => {
		    return (
		      <span>{record.status == '1' ? '已上架' : '未上架'}</span>
		    )
		  }
    },
    {
		  title: '建议零售价',
		  dataIndex: 'price',
		  key: 'price',
      width: '10%',
      render:(text) => text && text.toFixed(2)
		},  {
		  title: '已绑物料',
		  dataIndex: 'has_material',
		  key: 'has_material',
		  width: '8%',
		  render: (text, record) => {
		    return (
		      <span>{record.has_material ? '是' : '否'}</span>
		    )
		  }
		}
	]

	// 切换弹窗
  	const toggleModal = (flag) => {
	    dispatch({
	      type: 'recommendlist/toggleModal',
	      flag: flag
	    })
	    if (flag) {
	      dispatch({
	        type: 'recommendlist/productList',
	        payload: {
	          start: 0,
	          limit: 10
	        }
	      })
	    }
  	}

  	const onChangeProduct = (record) => {
	    if (record && record.length == 0) {
	      message.error("请选择商品项");
	      return;
	    }
	    let _temp = record.map((item) => {return {commodityId: item.id};});
      	dispatch({
	        type: 'recommendlist/doRecommend',
	        params: {
	          recommendGoods: _temp
	        }
      	})
  	}

  	const delRecommend = (selectedRows) => {
  		if (selectedRows && selectedRows.length == 0) {
	      message.error("请选择商品项");
	      return;
	    }
	    let _temp = selectedRows.map((item) => item.id);
	    dispatch({
	      type: 'recommendlist/delRecommend',
	      params: {
	      	recommendGoods: _temp
	      }
	    })
  	}

  	return (
	    <PageHeaderLayout title="推荐商品" breadcrumbList={breadcrumbList}>
      		<Page inner className={styles.productList}>
      			<div>
      				<GeneralFilter {...filterProps} onChange={handleFormChange}/>
      			</div>
      			<div className={styles.productBtns}>
      				<Button type="primary" onClick={() => delRecommend(selectedRows)}>批量删除</Button>
      				<Button type="primary" onClick={() => toggleModal(true)}>添加推荐商品</Button>
      			</div>
	  	    	<LwjTable {...tableProps} columns={columns}/>
          	</Page>
	        <Modal
	          visible={products.modalVisible}
	          title="商品池"
	          onOk={() => toggleModal(false)}
	          onCancel={() => toggleModal(false)}
	          width={950}
	          destroyOnClose={true}
	          footer={[
	            <Button key="back" onClick={() => toggleModal(false)}>关闭</Button>,
	          ]}>
	          <GeneralFilter {...productFilterProps} />
	          <div className={styles.productBtns}>
	            <Button type="primary" onClick={() => onChangeProduct(products.selectedRows)}>批量推荐</Button>
	          </div>
	          <LwjTable {...productTableProps} columns={productsColumns} />
	          <Loader spinning={loading.effects['recommendlist/link','recommendlist/alllink']} />
	        </Modal>
	    </PageHeaderLayout>
  	)
}


export default connect(({ recommendlist, app, loading}) => ({ recommendlist, app, loading}))(RecommendList)
